import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Category, SystemConfig } from '@/types'
import { categoryApi, systemApi } from '@/api'

export const useAppStore = defineStore(
  'app',
  () => {
    // 状态
    const categories = ref<Category[]>([])
    const systemConfig = ref<SystemConfig | null>(null)
    const networkStatus = ref<boolean>(true)

    // 计算属性
    const mainCategories = computed(() => {
      return categories.value.filter(cat => cat.level === 1 && cat.status === 'active')
    })

    /**
     * 获取分类列表
     */
    const fetchCategories = async () => {
      try {
        const res = await categoryApi.getList()
        categories.value = res.categories
      } catch (err) {
        console.error('获取分类列表失败:', err)
      }
    }

    /**
     * 根据ID获取分类
     */
    const getCategoryById = (id: number): Category | undefined => {
      return categories.value.find(cat => cat.id === id)
    }

    /**
     * 获取二级分类
     */
    const getSubCategories = (parentId: number): Category[] => {
      return categories.value.filter(
        cat => cat.parentId === parentId && cat.level === 2 && cat.status === 'active'
      )
    }

    /**
     * 获取系统配置
     */
    const fetchSystemConfig = async () => {
      try {
        const res = await systemApi.getConfigs()
        systemConfig.value = res
      } catch (err) {
        console.error('获取系统配置失败:', err)
      }
    }

    /**
     * 监听网络状态
     */
    const watchNetworkStatus = () => {
      uni.onNetworkStatusChange((res) => {
        networkStatus.value = res.isConnected
        if (!res.isConnected) {
          uni.showToast({
            title: '网络已断开',
            icon: 'none'
          })
        }
      })
    }

    /**
     * 初始化应用数据
     */
    const init = async () => {
      await Promise.all([
        fetchCategories(),
        fetchSystemConfig()
      ])
      watchNetworkStatus()
    }

    return {
      categories,
      systemConfig,
      networkStatus,
      mainCategories,
      fetchCategories,
      getCategoryById,
      getSubCategories,
      fetchSystemConfig,
      watchNetworkStatus,
      init
    }
  },
  {
    persist: {
      paths: ['categories', 'systemConfig']
    }
  }
)
